package com.ea.service.impl;

import com.ea.common.enums.OperationResultCode;
import com.ea.common.exception.ServiceException;
import com.ea.domain.dto.GoodsSalesDTO;
import com.ea.domain.entity.GoodsSalesInfo;
import com.ea.mapper.GoodsSalesInfoMapper;
import com.ea.service.IElectricGoodsSaleService;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author NAME-L
 * @Description TODO
 * @className IElectricGoodsSaleServiceImpl
 * @date 2023-01-30 20:17:22
 */
@Service
public class IElectricGoodsSaleServiceImpl implements IElectricGoodsSaleService {

    private static final Logger logger = LoggerFactory.getLogger(IElectricGoodsSaleServiceImpl.class);

    @Autowired
    private GoodsSalesInfoMapper salesInfoMapper;

    @Override
    public void addGoodsSale(GoodsSalesDTO salesDTO) {
        Long skuId = salesDTO.getSkuId();
        GoodsSalesInfo goodsSalesInfo = salesInfoMapper.selectGoodsSalesInfoBySkuId(skuId);
        if (goodsSalesInfo == null) {
            salesInfoMapper.insertGoodsSales(salesDTO);
        } else {
            BigDecimal newSales = salesDTO.getSalesVolume();
            BigDecimal allSales = newSales.add(goodsSalesInfo.getSalesVolume());
            salesInfoMapper.updateGoodsSalesBySkuId(skuId, allSales);
        }
    }

    @Override
    public void addGoodsSaleBatch(List<GoodsSalesDTO> salesDTOList) {
        if (CollectionUtils.isEmpty(salesDTOList)) {
            throw new ServiceException(OperationResultCode.SYSTEM_RECORD_GOODS_SALES);
        }
        List<Long> skuIdList = salesDTOList.stream().map(GoodsSalesDTO::getSkuId).collect(Collectors.toList());
        List<GoodsSalesInfo> salesInfoList = salesInfoMapper.selectGoodsSalesInfoBySkuIdBatch(skuIdList);
        List<Long> existsSkuIdList = salesInfoList.stream().map(GoodsSalesInfo::getSkuId).collect(Collectors.toList());
        List<GoodsSalesDTO> updateGoodsSaleList = new ArrayList<>();
        for (GoodsSalesDTO goodsSalesDTO : salesDTOList) {
            if (existsSkuIdList.contains(goodsSalesDTO.getSkuId())) {
                updateGoodsSaleList.add(goodsSalesDTO);
            }
        }
        // 移除已经存在销量的
        salesDTOList.removeIf(salesDTO -> existsSkuIdList.contains(salesDTO.getSkuId()));
        if (CollectionUtils.isNotEmpty(salesDTOList)) {
            // 新增销量
            salesInfoMapper.insertGoodsSalesBatch(salesDTOList);
        }
        if (CollectionUtils.isNotEmpty(updateGoodsSaleList)) {
            // 更新销量
            salesInfoMapper.updateGoodsSalesBySkuIdBatch(updateGoodsSaleList);
        }

    }


}
